package com.zhao.modleclass.fragment;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.zhao.modleclass.Helper.SpacesItemDecoration;
import com.zhao.modleclass.R;
import com.zhao.modleclass.adapter.LiveAdapter;
import com.zhao.modleclass.bean.LiveBean;
import com.zhao.modleclass.interfaces.IViewPager;
import com.zhao.modleclass.utils.Constant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by 张昭 on 2016/11/25.
 */

public class LiveFragment extends Fragment {
    private RecyclerView recyclerView_live;
    private Context mContext;
    private List<LiveBean.DataBean> mList = new ArrayList<>();
    private LiveAdapter mAdapter;
    private rx.Observable<LiveBean> observable;
    //声明刷新
    private int lastVisibleItem = 0;
    private ImageView toTopBtn;
    private Map<String, String> map;
    private SwipeRefreshLayout swipyRefreshLayout;
    public int page = 1;
    private LinearLayoutManager manager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_live, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView_live = (RecyclerView) view.findViewById(R.id.recyclerView_fragment_live);
        toTopBtn = (ImageView) view.findViewById(R.id.iv_live_gotop);
        swipyRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);

//置顶
        toTopBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回顶部
                recyclerView_live.scrollToPosition(0);
                //隐藏按钮
//                toTopBtn.setVisibility(View.GONE);
            }
        });

    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        map = new HashMap<>();
        map.put("pageSize", "10");
        map.put("pageNo", "1");
        Log.i("TAG", "----initGetData: " + map);
        manager = new LinearLayoutManager(mContext);
        //设置布局管理LayoutManager
        recyclerView_live.setLayoutManager(manager);
        //item高度固定 避免item重复的增删而浪费资源
        recyclerView_live.setHasFixedSize(true);
        //设置item之间的分割空间
        recyclerView_live.addItemDecoration(new SpacesItemDecoration(2));
        //公共的加载，默认加载第一页
        initpublic();
        //绑定适配器
        initGetData();
        //上拉刷新下拉加载
        initData();
    }

    private void initData() {
        swipyRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                map.put("pageNo", "1");
                initGetData();
                swipyRefreshLayout.setRefreshing(false);
            }
        });

        //上拉加载
        recyclerView_live.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem  == mAdapter.getItemCount() - 1) {
                    page ++;
                    map.put("pageNo", page + "");
                    initGetRefreData();
                    mAdapter.reloadRecyclerView(mList , false);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = manager.findLastVisibleItemPosition();
            }
        });

    }

    private void initpublic() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.Live_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        IViewPager iViewPager = retrofit.create(IViewPager.class);
        //加载每页内容
        observable = iViewPager.getJsonLiveString(map);
    }

    private void initGetData() {
        //观察者模式
        observable.subscribeOn(Schedulers.io())//切换线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<LiveBean>() {
                    @RequiresApi(api = Build.VERSION_CODES.ECLAIR_MR1)
                    @Override
                    public void call(LiveBean liveBean) {
                        mList = liveBean.getData();
                        Log.i("TAG", "onActivityCreated: ==========++++" + mList.size());
                        //初始化适配器
                        mAdapter = new LiveAdapter(mContext, mList, recyclerView_live);
                        //给recyclerview绑定适配器
                        recyclerView_live.setAdapter(mAdapter);
                    }
                });
    }
    private void initGetRefreData(){
        //观察者模式
        observable.subscribeOn(Schedulers.io())//切换线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<LiveBean>() {
                    @RequiresApi(api = Build.VERSION_CODES.ECLAIR_MR1)
                    @Override
                    public void call(LiveBean liveBean) {
                        mList=liveBean.getData();
                    }
                });
    }

}
